package com.imooc.shop.action;

import com.imooc.shop.bean.User;
import com.imooc.shop.service.ShopService;
import com.imooc.shop.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
@Slf4j
public class LoginServlet extends HttpServlet {
    private HttpServletRequest request;
    private HttpServletResponse response;

    private ShopService shopService;

    @Override
    public void init() throws ServletException {
        super.init();
        //获取sping的容器。然后从容器中得到业务层对象
        log.info("LoginServlet的init方法：获取sping的容器。然后从容器中得到业务层对象");
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        shopService = (ShopService) context.getBean("shopService");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.request = req;
        this.response = resp;
        String method = req.getParameter("method");
        if (method == null) {
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
        }
        switch (method) {
            case "getJsp":
                req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
                break;
            case "login":
                login();
                break;
        }
    }

    private void login() {
        try {
            log.info("LoginServlet的login方法开始执行");
            long start = System.currentTimeMillis();
            String loginName = request.getParameter("loginName");
            String passWord = request.getParameter("passWord");
            Map<String, Object> results = shopService.login(loginName, passWord);
            if ((int) results.get("code") == 0) {
                User user = (User) results.get("msg");
                request.setAttribute(Constants.USER_SESSION, user);
                response.sendRedirect(request.getContextPath() + "/list?method=getAll");
                long end = System.currentTimeMillis();
                log.info("登录成功！耗时：" + (end - start));
            } else {
                String msg = results.get("msg") + "";
                request.setAttribute("msg", msg);
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
